package com.shungen.apicloud.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shungen.apicloud.annotation.AuthCheck;
import com.shungen.apicloud.common.BaseResponse;
import com.shungen.apicloud.common.DeleteRequest;
import com.shungen.apicloud.common.ErrorCode;
import com.shungen.apicloud.common.ResultUtils;
import com.shungen.apicloud.constant.UserConstant;
import com.shungen.apicloud.exception.BusinessException;
import com.shungen.apicloud.exception.ThrowUtils;
import com.shungen.apicloud.model.dto.user.*;
import com.shungen.apicloud.model.entity.User;
import com.shungen.apicloud.model.vo.AccessTokenVo;
import com.shungen.apicloud.model.vo.LoginUserVO;
import com.shungen.apicloud.model.vo.UserVO;
import com.shungen.apicloud.service.UserService;
import com.shungen.apicloud.utils.AccessKeyGenerator;
import com.shungen.apicloud.utils.JWTUtil;
import com.shungen.apicloud.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;


/**
 * 用户接口
 *
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;


    @Resource
    private RedisUtil redisUtil;


    @Value("${user.pwd.salt}")
    public String USER_PWD_SALT;

    // region 登录相关

    /**
     * 用户注册
     * 直接使用邮箱作为用户账号，用户界面就可以直接显示用户名就可以了，保证邮箱唯一，节约字段
     * 注册后直接进入登录状态？
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<String> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String code = userRegisterRequest.getCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword,code)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"为空错误!");
        }
        Object o = redisUtil.get(userAccount);
        ThrowUtils.throwIf(o == null,ErrorCode.OPERATION_ERROR,"验证码失效！");
        String serverSaveCode = (String)o;
        ThrowUtils.throwIf(!serverSaveCode.equals(code),ErrorCode.OPERATION_ERROR,"验证码错误!");
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success("success");
    }

    /**
     * 用户登录(只验证，不返回用户信息)
     * 登录成功后数据部分填充token
     * 失败返回错误信息message
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<String> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        //1.校验参数
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2.验证登录，如果失败，里面会抛出异常
        User loginUser = userService.userLogin(userAccount, userPassword, request);
        // 3.这里其实已经拿到了用户的数据，提取出id、账号名和角色,生成token，返回
        Long id = loginUser.getId();
        String userName = loginUser.getUserName();
        String userRole = loginUser.getUserRole();
        HashMap<String,String> userMap = new HashMap<>();
        userMap.put("id",String.valueOf(id));
        userMap.put("userName",userName);
        userMap.put("userRole",userRole);
        String token = JWTUtil.generateToken(userMap);
        return ResultUtils.success(token);
    }




    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/getLoginUser")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        System.out.println("后端接收到token数据:" + token);
        ThrowUtils.throwIf(token == null,ErrorCode.PARAMS_ERROR,"未登录");
        if(!JWTUtil.verifyToken(token)){
            //token无效
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"token无效");
        }
        User user = null;
        try {
            //token有效
            long id = Long.parseLong(JWTUtil.getClaimFromToken(token, "id"));
            user = userService.getById(id);
        } catch (NumberFormatException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,e.getMessage());
        }
        return ResultUtils.success(userService.getLoginUserVO(user));
    }

    /**
     * 已登录用户更新个人信息
     *
     * @param userUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserUpdateMyRequest userUpdateMyRequest,
                                              HttpServletRequest request) {
        //检查登录状态
        String token = request.getHeader("token");
        ThrowUtils.throwIf(token == null,ErrorCode.NOT_LOGIN_ERROR,"未登录");
        ThrowUtils.throwIf(!JWTUtil.verifyToken(token),ErrorCode.PARAMS_ERROR,"token无效");
        long id = Long.parseLong(JWTUtil.getClaimFromToken(token, "id"));
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(id);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR,"更新用户信息失败");
        return ResultUtils.success(true);
    }
    // endregion


    //region 秘钥相关

    /**
     * 用户自己更新自己的accessKey和secretKey
     * @param request
     * @return
     */
    @AuthCheck
    @PostMapping("/accessToken/generate/my")
    public BaseResponse<AccessTokenVo> generateUserAccessKeyAndSecretKey(HttpServletRequest request){
        //获取用户id
        String token = request.getHeader("token");
        Long userId = Long.valueOf(JWTUtil.getClaimFromToken(token, "id"));
        //重新生成accessKey和secretKey
        String accessKey = AccessKeyGenerator.generateAccessKey();
        String secretKey = AccessKeyGenerator.generateSecretKey();
        boolean result = userService.updateAccessToken(userId, accessKey, secretKey);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR,"更新accessKey和secretKey失败");
        AccessTokenVo accessTokenVo = new AccessTokenVo(accessKey, secretKey);
        return ResultUtils.success(accessTokenVo);
    }


    /**
     * 返回当前登录用户的accessKey
     * @param request
     * @return
     */
    @AuthCheck
    @GetMapping("/accessToken/get/my")
    public BaseResponse<String> getAccessKey(HttpServletRequest request){
        //获取用户id
        String token = request.getHeader("token");
        Long userId = Long.valueOf(JWTUtil.getClaimFromToken(token, "id"));
        User loginUser = userService.getById(userId);
        ThrowUtils.throwIf(loginUser == null,ErrorCode.OPERATION_ERROR,"请求用户不存在");
        return ResultUtils.success(loginUser.getAccessKey());
    }


    //endregion



    // region 增删改查
    /**
     * 管理员端创建爱你用户
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        // 默认密码 12345678
        String defaultPassword = "12345678";
        String encryptPassword = DigestUtils.md5DigestAsHex((USER_PWD_SALT + defaultPassword).getBytes());
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,
            HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<UserVO> getUserVOById(long id, HttpServletRequest request) {
        BaseResponse<User> response = getUserById(id, request);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest,
            HttpServletRequest request) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        return ResultUtils.success(userPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest,
            HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<UserVO> userVO = userService.getUserVO(userPage.getRecords());
        userVOPage.setRecords(userVO);
        return ResultUtils.success(userVOPage);
    }

    // endregion


}
